﻿#region License
// Copyright (c) 2012 Mund Consulting Ltd
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Web.UI.WebControls;
using System.Collections;
using System.IO;
using Microsoft.SharePoint.Utilities;

namespace Mund.Sharepoint.Publishing
{
    public partial class CreatePage : LayoutsPageBase
    {
        const string constResource = "MundPublishingResource";
        const string constCoreResource = "wss";
        const string constBaseContentTypeId = "0x010100f2a9c1c92ef041a086f2feeaa284ff80";
        const string constBasePageLayout = "Basic Page Layout";
        const string constErrorMsg = "(No custom layout page found. Default system layout pages loaded.)";
        const string constBasicPagePath = "TEMPLATE\\1033\\STS\\DOCTEMP\\BLANKPGS\\bpstd.aspx";
        const string constLayoutLibraryName = "pageLayoutTitle";
        const string constDeafaultLibraryName="Pages";
        const string constContentTypeId = "ContentTypeId";
        const string constAssociatedContentType = "acType";
        const string constList = "List";
        const string constContentType = "ContentType";
        const string constTitle = "lstsetng_name_title";
        const string constComments = "versions_CommentsCol";
        const string constAspxExtention = ".aspx";
        bool isPageLayout=true;



        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                SPWeb curWeb = SPContext.Current.Web;
                SPList pageLayoutList = curWeb.Lists.TryGetList( Localization.GetValue( constResource, constLayoutLibraryName));

                if (pageLayoutList == null)
                {
                    lstbxPageTemplatePicker.Items.Add(new ListItem(constBasePageLayout));
                    isPageLayout = false;
                    lblMessage.Text = constErrorMsg;
                    return;            
                }

                string contentId = Request.QueryString[constContentTypeId];
                SPContentTypeId cID = new SPContentTypeId(contentId);
                SPListItemCollection itemCollection = pageLayoutList.Items;
                if (curWeb.AvailableContentTypes[new SPContentTypeId(constBaseContentTypeId)] != null)
                {
                    
                    int counter = 0;
                    foreach (SPListItem item in itemCollection)
                    {
                       // SPFieldMultiColumnValue val = (SPFieldMultiColumnValue)item[Localization.GetValue(constResource,constAssociatedContentType)];
                        SPFieldMultiColumnValue val = (SPFieldMultiColumnValue)item["AssociatedContentType"];
                        lstbxPageTemplatePicker.Items.Add(new ListItem("["+val[1]+"] " + item.Title, item.File.Url));
                        if (val[2]==cID.Parent.ToString() && lstbxPageTemplatePicker.SelectedIndex==-1)
                        {
                            lstbxPageTemplatePicker.SelectedIndex = counter;
                        }
                        counter++;
                    }
                    if (counter == 0)
                    {
                        isPageLayout = false;
                    }                    
                }
                else
                {
                    isPageLayout = false;
                }

                if (isPageLayout == false)
                {
                    lblMessage.Text = constErrorMsg;
                }
                lstbxPageTemplatePicker.Items.Add(new ListItem(constBasePageLayout));
 
            }
        }

        protected void CreateNewPage(object sender, EventArgs e)
        {            
            SPWeb curWeb = SPContext.Current.Web;
            SPFolder pagesFolder;
            SPListItem itm;
            string lstid = Request.QueryString[constList];

            if (string.IsNullOrEmpty(lstid))
            {
                pagesFolder = curWeb.GetFolder(constDeafaultLibraryName);
            }
            else
            {
                pagesFolder = curWeb.Lists[new Guid(lstid)].RootFolder;
            }

            string contentId = Request.QueryString[constContentTypeId];
            SPContentTypeId layoutContentId = new SPContentTypeId(contentId);
            SPFileCollection files = pagesFolder.Files;
            if (lstbxPageTemplatePicker.SelectedValue != constBasePageLayout)
            {
                SPFile spFileLayout = curWeb.GetFile(lstbxPageTemplatePicker.SelectedValue);
                pagesFolder.Files.Add(tbxPageUrlName.Text + constAspxExtention,spFileLayout.OpenBinary(),true);
                //spFileLayout.CopyTo(pagesFolder.Url + "/" + tbxPageUrlName.Text + constAspxExtention, true);
                SPFile spFile = pagesFolder.Files[pagesFolder.Url + "/" + tbxPageUrlName.Text + constAspxExtention];
                itm = spFile.Item;
                itm[constContentType] = curWeb.AvailableContentTypes[layoutContentId.Parent].Name;
            }
            else
            {
                string path = SPUtility.GetGenericSetupPath(constBasicPagePath);
                FileStream stream = new FileStream(path, FileMode.Open);
                SPFile spBasicPageFile = pagesFolder.Files.Add(pagesFolder.Url + "/" + tbxPageUrlName.Text + constAspxExtention, stream);
                stream.Close();
                itm = spBasicPageFile.Item;
                itm[constContentType] = constBasePageLayout;                
            }
            itm[Localization.GetValue(constCoreResource, constTitle)] = tbxTitle.Text;
            itm[Localization.GetValue(constCoreResource, constComments)] = tbxDescription.Text;
            curWeb.AllowUnsafeUpdates = true;
            itm.Update();
            curWeb.AllowUnsafeUpdates = false;
            Response.Redirect(curWeb.Url + "/" + pagesFolder.Url + "/" + tbxPageUrlName.Text + constAspxExtention);
            
        }

        protected void DoCancel(object sender, EventArgs e)
        {
            SPUtility.Redirect(string.Empty, SPRedirectFlags.UseSource, Context);
        }

    }
}
